#include <stdlib.h>
#include <stdio.h>

#include <debug.h>
#include <os_api.h>
#include <file_api.h>
#include <ext_api.h>
#include <hal/gpio.h>

#define TASK_STACK_SIZE (10 * 1024)
static char _task_stack[TASK_STACK_SIZE];

#define ESIM_CTRL0 GPIO_PIN_14
#define ESIM_CTRL1 GPIO_PIN_50
#define ESIM_CTRL2 GPIO_PIN_49

static int esim_set_switch(int simid)
{
    LOG_PRINTF("%s() simid %d", __func__, simid);
    switch (simid)
    {
    case 0:
        hal_GpioOut(ESIM_CTRL0, 1);
        hal_GpioOut(ESIM_CTRL1, 0);
        hal_GpioOut(ESIM_CTRL2, 0);
        break;
    case 1:
        hal_GpioOut(ESIM_CTRL0, 0);
        hal_GpioOut(ESIM_CTRL1, 1);
        hal_GpioOut(ESIM_CTRL2, 0);
        break;
    case 2:
        hal_GpioOut(ESIM_CTRL0, 0);
        hal_GpioOut(ESIM_CTRL1, 0);
        hal_GpioOut(ESIM_CTRL2, 1);
        break;
    }

    return simid;
}

static void esim_init(void)
{
    int simmode = -1;
    char *psm_str = NULL;

    hal_GpioSetDir(ESIM_CTRL0, GPIO_OUT_PIN);
    hal_GpioSetDir(ESIM_CTRL1, GPIO_OUT_PIN);
    hal_GpioSetDir(ESIM_CTRL2, GPIO_OUT_PIN);

    psm_str = psm_get_wrapper("esim", NULL, "simmode");
    if (psm_str)
    {
        simmode = atoi(psm_str);
        free(psm_str);
    }
    LOG_PRINTF("%s() Get simmode %d", __FUNCTION__, simmode);
}

static void esim_api_test(void)
{
    LOG_PRINTF("%s()... start...", __FUNCTION__);

    esim_init();
    ext_esim_setup_callback(esim_set_switch);
}

static void wlan_api_test(void)
{
    UINT32 cur_tick;
    UINT32 conn_sec;
    device_info_t device_info[10];
    int client_count, i;
    char buf_mac[18], buf_ip[16];
    char *px;

    cur_tick = OSAGetTicks();

    client_count = ext_wlan_get_device_list(device_info);
    for (i = 0; i < client_count; i++)
    {
        conn_sec = (cur_tick - device_info[i].Reg_Tick) / 200;

        px = device_info[i].MAC;
        snprintf(buf_mac, sizeof(buf_mac), "%02X:%02X:%02X:%02X:%02X:%02X", px[0], px[1], px[2], px[3], px[4], px[5]);

        px = device_info[i].IP;
        snprintf(buf_ip, sizeof(buf_ip), "%d.%d.%d.%d", px[0], px[1], px[2], px[3]);

        LOG_PRINTF("%s %s %s Time:%lu", __func__, buf_mac, buf_ip, conn_sec);
    }
}

static void app_task(void *param)
{
    unsigned count = 0;

    esim_api_test();

    // wait device to make data connection
    sleep(10); // 10 seconds

    while (1)
    {
        count++;
        LOG_PRINTF("%s test count %u", __func__, count);

        wlan_api_test();

        sleep(30);
    }
}

int main()
{
    int ret;
    OSTaskRef task_ref; // because following task will never exit, so we do not use task handle, so we don't care it's handle

    ret = OSATaskCreate(&task_ref, _task_stack, TASK_STACK_SIZE, OS_APP_PRIORITY, "app", app_task, NULL);
    ASSERT(ret == OS_SUCCESS);
}
